package com.ztools.wx.config;

import com.ztools.wx.handler.*;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.common.redis.WxRedisOps;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @Author:seeTools
 * @Date: 2023/4/9  11:37
 * @Version 1.0
 */
@AllArgsConstructor
@Configuration
public class WxMpConfig {

    private final Environment env;
    private final LogHandler logHandler;
    private final NullHandler nullHandler;
    private final ScanHandler scanHandler;
    private final StringRedisTemplate stringRedisTemplate;
    private final SubscribeHandler subscribeHandler;
    private final UnsubscribeHandler unsubscribeHandler;

    @Bean
    public WxMpService wxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpRedisConfig());
        return wxMpService;
    }

    @Bean
    public WxMpRedisConfigImpl wxMpRedisConfig() {
        String keyPrefix = env.getProperty("wx.keyprefix");
        WxRedisOps wxRedisOps = new RedisTemplateWxRedisOps(stringRedisTemplate);
        WxMpRedisConfigImpl wxMpRedisConfig = new WxMpRedisConfigImpl(wxRedisOps, keyPrefix);
        wxMpRedisConfig.setAppId(env.getProperty("wx.appid"));
        wxMpRedisConfig.setSecret(env.getProperty("wx.appsecret"));
        wxMpRedisConfig.setToken(env.getProperty("wx.token"));
        return wxMpRedisConfig;
    }

    @Bean
    public WxMpMessageRouter wxMpMessageRouter(WxMpService wxMpService) {
        final WxMpMessageRouter router = new WxMpMessageRouter(wxMpService);
        // 记录所有日志（异步执行）
        router.rule().handler(logHandler).next();
        // 关注事件
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SUBSCRIBE).handler(subscribeHandler).end();
        // 取消关注
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.UNSUBSCRIBE).handler(unsubscribeHandler).end();
        // 扫码事件
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SCAN).handler(scanHandler).end();
        // 模板消息发送成功事件
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.TEMPLATE_SEND_JOB_FINISH).handler(nullHandler).end();
        // 点击菜单链接事件
        router.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.VIEW).handler(nullHandler).end();
        // 默认事件
        return router;
    }

}
